package cn.wolfcode.web.controller;

import cn.wolfcode.ssm.domain.Department;
import cn.wolfcode.ssm.domain.Employee;
import cn.wolfcode.ssm.domain.Role;
import cn.wolfcode.ssm.page.JsonPage;
import cn.wolfcode.ssm.page.PageResult;
import cn.wolfcode.ssm.query.EmployeeQueryObject;
import cn.wolfcode.ssm.service.IDepartmentService;
import cn.wolfcode.ssm.service.IEmployeeService;
import cn.wolfcode.ssm.service.IRoleService;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/employee")

public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private IRoleService roleService;

    @RequestMapping("/list")
    public String list(Model model,@ModelAttribute("qo") EmployeeQueryObject qo){
        PageInfo<Employee> pageResult = employeeService.query(qo);
        model.addAttribute("pageResult",pageResult);


        List<Department> departments = departmentService.selectAll();
        model.addAttribute("departments",departments);
        return "/employee/list";
    }

    @RequestMapping("/delete")
    @ResponseBody
    public JsonPage delete(Long id){
        try {
            if (id != null){
                employeeService.delete(id);
            }
            return new JsonPage(true,"操作成功");
        }catch (Exception e){
            e.printStackTrace();
            return new JsonPage(false,"操作失败");
        }

    }

    @RequestMapping("/input")
    public String input(Model model, Long id){
        List<Department> departments = departmentService.selectAll();
        model.addAttribute("departments",departments);
        List<Role> roles = roleService.selectAll();
        model.addAttribute("roles",roles);

        if (id != null){
            Employee employee = employeeService.get(id);
            model.addAttribute("employee",employee);
        }
        return "/employee/input";
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public JsonPage saveOrUpdate(Employee employee, Long[] ids){
        try {
            if (employee.getId() != null){
                employeeService.update(employee,ids);
            }else{
                employeeService.save(employee,ids);
            }
            return new JsonPage();
        }catch (Exception e) {
            e.printStackTrace();
            return new JsonPage(false,"操作失败");
        }
    }

    // 修改密码
    @RequestMapping("/updatePwd")
    public String updatePwd(){

        return "update/updatePwd";
    }
   // 重置密码
    @RequestMapping("/reset")
    public String resetPwd(Model model, Long id){
        if (id != null){
            Employee employee = employeeService.get(id);
            model.addAttribute("employee",employee);
        }
        return "reset/resetPwd";
    }

    // 批量删除
    @RequestMapping("/batchDelete")
    @ResponseBody
    public JsonPage batchDelete(Long[] ids){
       try {
           employeeService.batchDelete(ids);
           return new JsonPage();
       }catch (Exception e){
           return new JsonPage(false,"操作失败");
       }
    }


    // 验证用户名是否存在

    /**
     * 需要传回去的是valid 当valid为true,则是通过,为false是不通过
     * @param name
     * @return
     */
//    @RequestMapping("/checkName")
//    @ResponseBody
//    public HashMap checkName(String name, Long id){
        // 第一种方法
//        // 执行一个Sql语句通过传过来的员工作为判断员工是否存在,不存在员工就为null
//        Employee employee = employeeService.checkName(name);
//        // new一个HashMap
//        HashMap<Object, Object> map = new HashMap<>();
//        // 把valid作为key 员工为空做为value ,也就是员工为空时是true
//        map.put("valid",employee==null);
        // 返回回去
//     return map;
 //    }

        // 第二种方法.传了id和name过来
        @RequestMapping("/checkName")
        @ResponseBody
        public HashMap checkName(String name, Long id){
            // new一个HashMap
        HashMap<Object, Object> map = new HashMap<>();
        // 如果id为空,则是新增
        if (id == null){
            // 这是判断用户名是否存在
            Employee employee = employeeService.checkName(name);
            // 如果不存在,employee==null情况就是true,这时候把它装在map中返回回去
            map.put("valid",employee==null);
            return map;
        }
            // 如果id不为空,则是编辑方法,
            // 根据用户传上来的id去获取此id人的名字,和传上来的名字比较,相同也为true

            String oldName = employeeService.selectById(id);
            if (oldName.equals(name)){
                map.put("valid" ,true);
                return map;
            }
            // 如果用户修改了名字,在在判断修改的这个名字在数据库中有没有存在对象;
            // 如果没有则返回true
            Employee employee = employeeService.checkName(name);
            map.put("valid", employee == null);
            return map;


        }

     // 判断用户状态是否异常
    @RequestMapping("/status")
    public String status(Long id){
        if (id != null){
            // 通过id拿到对象
            Employee employee = employeeService.get(id);
            // 如果对象的status是true就设置成false,是false就该陈true
            employee.setStatus(employee.isStatus()? false:true);
            // 执行一个sql语句.只修改status的状态的
            employeeService.updateStatus(employee);
        }
        return "redirect:/employee/list.do";
    }

    // 导出
    @RequestMapping("/exportXls")
    public void  exportXls(HttpServletResponse resp)throws IOException{
        // 文件下载的响应头（让浏览器访问资源的的时候以下载的方式打开）
        resp.setHeader("Content-Disposition","attachment;filename=employee.xls");
        // 调用方法
        Workbook wb = employeeService.exportXls();
        // 输出流(输出下载文件)
        wb.write(resp.getOutputStream());
    }


    // 导入
    @RequestMapping("/importXls")
    @ResponseBody
    public JsonPage importXls(MultipartFile file){
            employeeService.importXls(file);
            return new JsonPage();
    }



}

